package com.focusai.efairy.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.focusai.efairy.R;
import com.focusai.efairy.model.request.PutPasswdRequest;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.ActivityUtils;

/**
 * Created by luo_guangwen on 2018/1/16.
 */

public class ChangePasswdActivity extends SwipeBackBaseActivity {

    private EditText oldPasswdEdit;
    private EditText newPasswdEdit1;
    private EditText newPasswdEdit2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_passwd_change);
        setCenterTitleName("修改密码");
        initView();
        bindEvents();
    }

    @Override
    protected void initView() {
        oldPasswdEdit = findView(R.id.et_old_pw);
        newPasswdEdit1 = findView(R.id.et_old_pw1);
        newPasswdEdit2 = findView(R.id.et_old_pw2);
    }

    @Override
    protected void bindEvents() {
        findView(R.id.btn_login_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkInput()) {
                    sendPwd(oldPasswdEdit.getText().toString(), newPasswdEdit1.getText().toString());
                }
            }
        });
    }

    private boolean checkInput() {
        String old = oldPasswdEdit.getText().toString();
        String new1 = newPasswdEdit1.getText().toString();
        String new2 = newPasswdEdit2.getText().toString();
        if (TextUtils.isEmpty(old)) {
            showToast("请输入原密码");
            return false;
        }
        if (TextUtils.isEmpty(new1)) {
            showToast("请输入新密码");
            return false;
        }
        if (TextUtils.isEmpty(new2)) {
            showToast("请再次输入新密码");
            return false;
        }
        if (!new1.equals(new2)) {
            showToast("前后两次输入的密码不相同");
            return false;
        }
        return true;
    }

    private void sendPwd(String oldPasswd, String newPasswd) {
        HttpManager.getInstance().sendRequest(new PutPasswdRequest(oldPasswd, newPasswd, new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                showToast("修改密码成功");
                loginOut();
            }

            @Override
            protected void onFail(NetworkException exception) {
                showToast(exception.getErrorMessage());
            }
        }));
    }

    private void loginOut(){
        ActivityUtils.cleanAndStartLoginActivity(ChangePasswdActivity.this);
        setResult(RESULT_OK);
        finish();
    }
}
